f = open('report.txt', encoding='utf-8')
f. readline()
data_report = f.readlines()
lines_new = []
lines_new2 = []
lines_new3 = []
lines_ranking = []
#统计个人总成绩和平均分
def personalscores():
    for line in data_report:
        line = line.strip()
        score = line.split(' ')
        score_int = list(map(int, score[1:])) #如何用sum函数？？
        sum_score = sum(score_int)
        average_score = '%.1f' % (sum_score/len(score[1:]))
        score.append(str(sum_score))
        score.append(average_score)
        line = ' '.join(score) + '\n'
        lines_new.append(line)
personalscores()


#根据总分排序
def ranking():
    lines_temp = []
    for line in lines_new:
        score = line.split()
        lines_temp.append(score)
    lines_temp.sort(key=lambda x:x[-2], reverse= True)
    for line2 in lines_temp:
        score2 = " ".join(line2) + '\n'
        lines_new2.append(score2)
ranking()

#计算各科平均分
def averagescores():
    averagescore = []
    lines_new_copy = lines_new2
    for i in range(1,12): #如何优化为不用数科目数？
        sum_score = 0
        for line in lines_new_copy: #单科平均分
            line = line.strip()
            score = line.split(' ')
            sum_score += eval(score[i])
        average_score = '%.1f' % (sum_score/len(lines_new))
        averagescore.append(average_score)
    line1 = '平均 ' + ' '.join(averagescore) + '\n' #第一行数据
    lines_new2.insert(0,line1)
averagescores()

#小于60改为不及格
def replace_to_fail():
    for line in lines_new2:
        line = line.strip()
        score = line.split(' ')
        score2 = ['不及格' if eval(x) < 60 else x for x in score[1:]]
        score3 = score2.insert(0,score[0])
        line_fail = ' '.join(score2) + '\n'
        lines_new3.append(line_fail)
replace_to_fail()


#加上排名
def ranking_number():
    i = 0
    for line in lines_new3:
        line = str(i) + ' ' + line
        lines_ranking.append(line)
        i += 1
ranking_number()

#生成新文档
line0 = '名次 姓名 语文 数学 英语 物理 化学 生物 政治 历史 地理 总分 平均分\n'
lines_ranking.insert(0,line0)
f2 = open('result.txt', 'w', encoding='utf-8')
f2.writelines(lines_ranking)
f.close()
f2.close()













